#include "emailsender.h"
#include "../mainframe/mailsettingsdialog.h"
#include "smtpmime.h"

#include <QSettings>
#include <QFile>

EmailSender::EmailSender(const QStringList &toList, const QStringList &attaList, QObject *parent) :
    m_toList(toList),
    m_attaList(attaList),
    QObject(parent)
{
}

void EmailSender::sendMail()
{
    emit progress(0);

    QSettings s;
    SmtpClient smtp(s.value(MAIL_SERVER).toString(), 25, SmtpClient::TcpConnection);

    MimeMessage msg;
    EmailAddress from(s.value(MAIL_FROM).toString());
    msg.setSender(&from);
    QList<EmailAddress*> toList;
    msg.setSubject(s.value(MAIL_SUBJECT).toString());
    foreach (const QString &to, m_toList) {
        EmailAddress *t = new EmailAddress(to);
        toList << t;
        msg.addRecipient(t);
    }

    MimeHtml body(s.value(MAIL_BODY).toString());
    msg.addPart(&body);

    QList<MimeAttachment*> attaList;
    foreach (const QString &atta, m_attaList) {
        MimeAttachment *a = new MimeAttachment(new QFile(atta));
        attaList << a;
        msg.addPart(a);
    }

    emit progress(10);

    if (!smtp.connectToHost()) {
        emit finished(false, tr("Connection Failed"));
        return;
    }

    emit progress(20);

    if (!smtp.login(s.value(MAIL_USERNAME).toString(), s.value(MAIL_PASSWORD).toString())) {
        emit finished(false, tr("Authentification Failed"));
        return;
    }

    emit progress(30);

    if (!smtp.sendMail(msg)) {
        emit finished(false, tr("Mail sending failed"));
        return;
    }

    emit progress(100);

    smtp.quit();
    qDeleteAll(toList);
    qDeleteAll(attaList);
    emit finished(true, tr("Mail sent successfully"));
}
